package com.hmall.order.listener;

import com.hmall.common.feign.ItemServiceFeign;
import com.hmall.common.pojo.Item;
import com.hmall.common.pojo.vo.ItemVo;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;


@Slf4j
@Component
public class SpringRabbitListener {

    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private ItemServiceFeign itemServiceFeign;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.order.ispay"),
            exchange = @Exchange(name = "dl.direct"),
            key = "ispay"
    ))
    public void removeItemListen(String orderID) {
        log.info("订单ID判断是否超时.....{}", orderID);

        Order order = iOrderService.getById(orderID);

        if(5 == order.getStatus())
            return;
        if(1 != order.getStatus())
            return;

        log.info("订单ID.....{}，，，超时", orderID);

        List<OrderDetail> orderDetailList = iOrderService.orderDetailByOrderID(orderID);

        iOrderService.updateById(
                Order.builder()
                    .id(Long.valueOf(orderID))
                    .status(5)
                    .build()
        );

        for (OrderDetail orderDetail : orderDetailList) {
            ItemVo info = itemServiceFeign.info(String.valueOf(orderDetail.getItemId()));
            itemServiceFeign.update(
                    Item.builder()
                            .id(orderDetail.getItemId())
                            .stock(info.getStock()+1)
                            .build()
            );
        }
    }

    // 处理消息失败的消费者
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.q.order.error"),
            exchange = @Exchange(name = "dl.ex.order.error", type = ExchangeTypes.TOPIC),
            key = "error"
    ))
    public void errorItem(Message message) {
        Map<String, Object> headers = message.getMessageProperties().getHeaders();
        headers.entrySet().forEach(e -> {
            log.info("key:{},,,val:{}", e.getKey(), e.getValue());
        });
    }
}
